package tencent

import (
	"context"
	"fmt"
	sms "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sms/v20210111"
	"go.uber.org/zap"
)

type Service struct {
	client   *sms.Client
	appId    *string
	signName *string
}

func NewService(c *sms.Client, appId, signName string) *Service {
	return &Service{
		client:   c,
		appId:    &appId,
		signName: &signName,
	}
}

func (s *Service) Send(ctx context.Context, tplId string, args []string, numbers ...string) error {
	req := sms.NewSendSmsRequest()
	req.PhoneNumberSet = toStringPtrSlice(numbers)
	req.SmsSdkAppId = s.appId
	req.TemplateId = &tplId
	//ctx继续往下传
	req.SetContext(ctx)
	req.TemplateParamSet = toStringPtrSlice(args)
	req.SignName = s.signName
	resp, err := s.client.SendSms(req)
	zap.L().Debug("调用腾讯短信服务", zap.Any("req", req), zap.Any("resp", resp))
	if err != nil {
		return err
	}

	for _, status := range resp.Response.SendStatusSet {
		if status.Code == nil || *(status.Code) != "ok" {
			return fmt.Errorf("发送失败， code: %s, 原因: %s", *status.Code, *status.Message)
		}
	}

	return nil
}

func toStringPtrSlice(src []string) []*string {
	return SliceMap(src, func(idx int, src string) *string {
		return &src
	})
}

func SliceMap(src []string, m func(idx int, src string) *string) []*string {
	dst := make([]*string, len(src))
	for i, s := range src {
		dst[i] = m(i, s)
	}
	return dst
}
